/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package utfpr.cp.model;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import semanticrawler.Main;
import semanticrawler.MainAppControl;

/**
 *
 * @author Adriano_2
 */
public class DAO {

    protected EntityManager em;
    
    public DAO(EntityManager em) {
        this.em = em;
    }
    
    protected void begin() {
        em.getTransaction().begin();
    }
    
    protected void commit() {
        em.getTransaction().commit();
    }
    
    protected static EntityManagerFactory emf;
    public static EntityManagerFactory getFactory() {
        if (emf == null) {
            emf = Persistence.createEntityManagerFactory("default");
        }
        return emf;
    }
    
    public static void closeFactory() {
        if (emf != null && emf.isOpen()) {
            emf.close();
        }
        emf = null;
    }
    
    public static EntityManager getEntity() {
        return getFactory().createEntityManager();
    }
    
    public EntityManager getCurrentEntity() {
        return em;
    }
    
    public static boolean save(Object obj) {
        return save(obj, getEntity());
    }
    
    public static boolean save(Object obj, EntityManager em) {
        try {
            if (em.getTransaction().isActive()) {
                em.persist(obj);
            }
            else {
                em.getTransaction().begin();
                em.persist(obj);
                em.getTransaction().commit();
            }
            return true;
        }
        catch (Exception e) {
            Logger.getLogger(MainAppControl.class.getName()).log(Level.SEVERE, null, e);
        }
        return false;
    }
    
    public static boolean delete(Object obj) {
        return delete(obj, getEntity());
    }
    
     public static boolean delete(Object obj, EntityManager em) {
         try {
            if (em.getTransaction().isActive()) {
                em.remove(em.merge(obj));
            }
            else {
                em.getTransaction().begin();
                em.remove(em.merge(obj));
                em.getTransaction().commit();
            }
            return true;
        }
        catch (Exception e) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
        }
        return false;
     }
}
